<?php

namespace app\admin\controller\bargain;

use app\common\controller\AdminController;
use app\common\service\store\BargainService;
use app\common\service\store\GoodsService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * @ControllerAnnotation(title="bargain")
 */
class Bargain extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\bargain\Bargain();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);

            $data = BargainService::createBargainGoods($post);
            $data['code'] == 200 ? $this->success($data['message']) : $this->error($data['message']);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        //获取砍价活动对应的商品
        $image = GoodsService::getSkuImages($id)[0];
        $row['goods_id'] = GoodsService::getGoodsId($id);
        $row['goods_image'] = GoodsService::getGoodsImages($row['goods_id'])[0];
        $row['start_time'] = timeToDate($row['start_time']);
        $row['end_time'] = timeToDate($row['end_time']);
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        $this->assign('image', $image);
        return $this->fetch();
    }
}